import React,{useState,useEffect} from 'react';
import {connect} from 'react-redux';
import {userAction} from '../../store/actions';
import {useHistory} from 'react-router';
import {testPhone,testPassword} from '../../utils/regexp';
import style from './index.module.scss';
interface Iprops{
    loginProps:(username:string,password:string)=>void,
    isLogin:boolean
}
const Login: React.FC<Iprops> = props => {
    const history = useHistory();
    const [username,setUsername] = useState('15323807318');
    const [password,setPassword] = useState('123456');
  
    useEffect(()=>{
        if(props.isLogin){
            const params = history.location.search.slice(1).split('&');
            const paramsObj:{[key:string]:any} = {};
            params.forEach(item=>{
                const paramsArr = item.split('=');
                paramsObj[paramsArr[0]] = decodeURIComponent(paramsArr[1])
            })
            history.replace(paramsObj['redirect'] || '')
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    },[props.isLogin])

    const login = ()=>{
        (window as any)._hmt.push(['_trackEvent', '登录', '登录按钮']);
        if(!testPhone.test(username)) return alert('手机号格式不正确');
        if(!testPassword.test(password)) return alert('密码格式不正确');
        props.loginProps(username,password)
    }
    return <div className={style.login}>
        <div className={style.wrap}>
            <img src={require('../../assets/img/logo2.png')} alt="" />
        </div>
        <div className={style.content}>
            <p>
                <input type="text" value={username} onChange={e=>setUsername(e.target.value)} placeholder="输入用户账号"/>
            </p>
            <p>
                <input type="password" value={password} placeholder="输入用户密码" onChange={e=>setPassword(e.target.value)}/>
            </p>
        </div>
        <div className={style.footer}>
            <button onClick={login}>登录</button>
        </div>
    </div>
}
const mapStateToProps=(state:any)=>{
    return state.user
}
const mapDispatchToProps=(dispatch:Function)=>{
    return {
        loginProps:(username:string,password:string)=>{
            dispatch(userAction(username,password))
        }
    }
}
export default connect(mapStateToProps,mapDispatchToProps)(Login)
